package com.itheima.config;

import com.itheima.dao.AccountDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;


public class MybatisConfig {
    /*
      SqlSessionFactoryBean (mybatis的spring整合包提供的类)
      1. 底层会提供 SqlSessionFactory
      2. 当开发者需要注入dao层bean的,此SqlSessionFactory会自动提供, 省略过程变量
          1). 还需要设置dao层的扫描
   */
    @Bean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource ds){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置pojo的包扫描
        factoryBean.setTypeAliasesPackage("com.itheima.domain");
        //设置连接池
        factoryBean.setDataSource(ds);

        return factoryBean;
    }
    //定义bean，返回MapperScannerConfigurer对象(mybatis的spring整合包提供的类)
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        //设置dao层的接口扫描
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }

//    @Bean
//    public SqlSessionFactoryBuilder getSqlSessionFactoryBuilder(){
//        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//
//        return builder;
//    }
//
//    @Bean
//    public SqlSessionFactory getSqlSessionFactory(SqlSessionFactoryBuilder builder) throws IOException {
//        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//        SqlSessionFactory sessionFactory = builder.build(inputStream);
//
//        return sessionFactory;
//
//    }
//
//    @Bean
//    public SqlSession getSqlSession(SqlSessionFactory sessionFactory)  {
//        SqlSession sqlSession = sessionFactory.openSession(true);
//        return sqlSession;
//
//    }
//
//    @Bean
//    public AccountDao getAccountDao(SqlSession sqlSession){
//        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
//        return accountDao;
//    }

}
